package com.simba.server.task;

import com.simba.common.log.LogUtil;
import com.simba.common.utils.StringUtil;
import com.simba.server.commands.impl.update.RenewBarcodeInfoExpiredCmd;
import com.simba.server.components.CommandExecutor;
import com.simba.server.components.data.SortInfo;
import org.apache.log4j.Logger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class UpdatePacketExpiredTask extends Thread {
    public static final Logger logger = Logger.getLogger(UpdatePacketExpiredTask.class);
    private final BlockingQueue<SortInfo> queue = new LinkedBlockingQueue<>();

    public UpdatePacketExpiredTask()
    {
        this.setName("packet-expired-Task");
    }

    public void offerPacketExpiredToQueue(SortInfo info)
    {
        if (info == null)
        {
            return;
        }
        this.queue.offer(info);
    }

    @Override
    public void run()
    {
        while (!Thread.currentThread().isInterrupted())
        {
            try
            {
                this.updatePacketExpiredList();
            }
            catch (Exception e)
            {
                if (e instanceof InterruptedException)
                {
                    Thread.currentThread().interrupt();
                }
                LogUtil.LogError(UpdatePacketExpiredTask.logger, "Handle packet expired error:  " + e);
            }
        }
    }

    private void updatePacketExpiredList() throws InterruptedException
    {
        SortInfo info = this.queue.take();

        if (StringUtil.isNull(info.getBarcode()))
        {
            return;
        }

        CommandExecutor.executorSqlCommand(RenewBarcodeInfoExpiredCmd.NAME, info.getBarcode(),false);
    }
}
